<template>
  <div>
    <el-tag
    v-for="tag in dynamicTags"
    :key="tag"
    class="mx-1"
    closable
    :disable-transitions="false"
    @close="handleClose(tag)"
  >
    {{ tag }}
  </el-tag>
  <el-input
    v-if="inputVisible"
    ref="InputRef"
    v-model="inputValue"
    class="tag-input"
    size="small"
    @keyup.enter="handleInputConfirm"
    @blur="handleInputConfirm"
  />
  <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
    添加
  </el-button>
  <div style="text-align:left">标签最大个数为:{{limit}}个</div>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, ref, onMounted } from 'vue'
import { ElInput } from 'element-plus'
const props = defineProps({
  list: {
    required: true,
    type: Array<string>
  },
  limit: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['changeTags'])

const inputValue = ref('')
const tags:Array<string> = []
const dynamicTags = ref(tags)
const inputVisible = ref(false)

onMounted(() => {
  dynamicTags.value = JSON.parse(JSON.stringify(props.list)) // 引用传递单项数据流需要更改
})
const InputRef = ref<InstanceType<typeof ElInput>>()

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  emit('changeTags', dynamicTags.value)
}

const showInput = () => {
  if (props.list.length < props.limit) {
    inputVisible.value = true
    nextTick(() => {
    InputRef.value!.input!.focus()
    })
  }
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
  emit('changeTags', dynamicTags.value)
}
</script>
<style lang="scss" scoped>
.tag-input{
  display: inline-block;
  width: 100px;
}
</style>
